package logic

import (
	"context"
	"userop_srv/global"
	"userop_srv/model"
	"userop_srv/userop_proto"

	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// 获取收藏列表
func (s *Server) GetFavList(ctx context.Context, in *userop_proto.UserFavRequest) (*userop_proto.UserFavListResponse, error) {
	var userFavs []model.UserFav
	var userFavList []*userop_proto.UserFavResponse
	//查询用户的收藏记录
	//查询某件商品被哪些用户收藏了
	result := global.DB.Where(&model.UserFav{UserId: in.UserId, GoodsId: in.GoodsId}).Find(&userFavs)

	for _, userFav := range userFavs {
		userFavList = append(userFavList, &userop_proto.UserFavResponse{
			UserId:  userFav.UserId,
			GoodsId: userFav.GoodsId,
		})
	}

	return &userop_proto.UserFavListResponse{
		Total: int32(result.RowsAffected),
		Data:  userFavList,
	}, nil
}

// 收藏
func (s *Server) AddUserFav(ctx context.Context, in *userop_proto.UserFavRequest) (*userop_proto.UserFavEmpty, error) {
	var userFav model.UserFav

	userFav.UserId = in.UserId
	userFav.GoodsId = in.GoodsId

	global.DB.Save(&userFav)

	return &userop_proto.UserFavEmpty{}, nil
}

// 删除收藏
func (s *Server) DeleteUserFav(ctx context.Context, in *userop_proto.UserFavRequest) (*userop_proto.UserFavEmpty, error) {
	if result := global.DB.Unscoped().Where("goods_id=? and user_id=?", in.GoodsId, in.UserId).Delete(&model.UserFav{}); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "收藏记录不存在")
	}
	return &userop_proto.UserFavEmpty{}, nil
}

// 获取收藏详情
func (s *Server) GetUserFavDetail(ctx context.Context, in *userop_proto.UserFavRequest) (*userop_proto.UserFavEmpty, error) {
	var userfav model.UserFav
	if result := global.DB.Where("goods_id=? and user_id=?", in.GoodsId, in.UserId).Find(&userfav); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "收藏记录不存在")
	}
	return &userop_proto.UserFavEmpty{}, nil
}
